<template>
	<view class="filter-model">
		<view class="model-content" @click="showFuc">
			<view class="imgBox">
				<image src="@/static/images/index/selectA.png" mode="" v-if="activeTxt"></image>
				<image src="@/static/images/index/selectD.png" mode="" v-else></image>
			</view>
			<view class="model-content-title" :style="{ color: activeTxt ? '#0091ff' : '#333' }">{{ '筛选' }}

			</view>
		</view>
		<filter-drawer :chooseData="choosed" :filterList="filterList" :comfireText="comfireText" :show="showFilter"
			:keyMap="keyMap" :title="['保养工单筛选', '维修工单筛选', '配件工单筛选'][orderType]" ref="filter-drawer"
			:isShowTemplate="orderType == 0 ? true : false" :isShowPart="orderType == 2 ? true : false"
			:isShowDate="typeForm == 2 ? true : false" @closed="handleClose" @submit="submitFilter"
			@chooseTag="getResultCount"></filter-drawer>
		<time-select v-if="selectTimePopup" :beforeToday="true" :atterToday="true" :isChooseToday="true"
			@close="closeSelectTimePopup"></time-select>
	</view>
</template>

<script>
import filterDrawer from './filter-drawer/filterDrawer.vue';
import { getNowTime } from '@/utils/utils.js';
import { timeLiness, duration, signType } from '@/apis/workOrder.js';
import { orderReordByOld, orderReordWxOld, orderReordPjOld } from '@/apis/workOrder.js';
import { problemItem, getPart } from '@/apis/barrierSearch.js';
// import { getElevatorList } from '@/apis/barrierSearch.js';
import { removeEmpty } from '@/utils/utils.js';
import timeSelect from '@/pages/index/components/timeSelect.vue';
export default {
	name: 'filter-model',
	components: { filterDrawer, timeSelect },
	props: {
		disabled: {
			type: Boolean,
			default: false
		},
		all: {
			type: Boolean,
			default: true
		},
		csd: {
			type: Object,
			default: () => {
				return {};
			}
		},
		userIds: {
			type: String,
			default: ''
		},
		orderType: {
			type: Number
		},
		elevatorId: {
			type: String
		},
		dateOpt: {
			type: Object
		},
		// 从哪个页面跳进来2为个人工单页面,需要展示时间
		typeForm: {
			type: String
		},
		keyword: {
			type: String,

		},
		// 如果从绩效跳跳过来就是要开始和结束时间
		start: {
			type: String,
			default: ''
		},
		end: {
			type: String,
			default: ''
		}

	},
	watch: {
		dateOpt: {
			handler: (val, olVal) => {
				console.log('我变化了', val, olVal);
			},
			deep: true,
			immediate: true
		},
		showFilter(val) {
			this.$emit('showFilterChange', val);
		}
	},
	data() {
		return {
			filterList: [],
			choosed: {},
			showFilter: false,
			allChecked: true,
			chooseArr: [],  // 选中的标签arr
			comfireText: '确定',
			keyMap: {},
			startTime: '',
			isShowTemplate: true,
			dateObj: {
				startTime: '',
				endTime: '',
				value: ''
			},
			activeTxt: false,
			selectTimePopup: false,
		};
	},
	created() {
		// this.initModel();
		this.allChecked = this.all;
		this.choosed = JSON.parse(JSON.stringify(this.csd));
		// 给日期组件赋值

		setTimeout(() => {
			this.setChooseArr();
		}, 500);
		uni.$on('getCustomerSwitch', (data) => {
			this.selectTimePopup = data;
		});
	},
	beforeDestroy() {
		uni.$off('getCustomerSwitch'); 
	},
	computed: {
		showConditions() {
			let flag = false;
			flag = this.allChecked || Object.keys(this.choosed).length === 0 ? true : false;
			return flag;
		}
	},

	methods: {
		// 自定义日期
		closeSelectTimePopup(res) {
			let start = '';
			let end = '';
			if (res) {
				// console.log("自定义日期", res);
				if (res.indexOf('-') != -1) {
					const timeArr = res.split('-');
					start = timeArr[0].replaceAll('.', '-');
					end = timeArr[1].replaceAll('.', '-');
				} else {
					const time = res.replaceAll('.', '-');
					start = time;
					end = time;
				}
				const nowDay = getNowTime();
				let nowtime = new Date(nowDay).getTime();
				let starttime = new Date(start).getTime();
				let endtime = new Date(end).getTime();
				if (endtime >= nowtime) {
					console.log('包含今天');
					uni.showToast({
						title: '自定义日期范围须小于今天',
						icon: 'none',
					});
					return;
				}
			} else {
			}
			this.selectTimePopup = false;
			uni.$emit('closeTimeSelect', { start, end });
		},
		// 重置处理
		reset() {
			this.$refs['filter-drawer'].handleReset();
		},
		async initModel(index) {
			console.log(this.typeForm, '类型');
			let all = [];
			this.filterList = [];
			if (index == 0) {
				all = [timeLiness(), duration(), signType()];
				await Promise.all(all).then(res => {
					if (res) {
						let taskMap = {
							0: {
								title: '及时性',
								key: 'timeliness'
							},
							1: {
								title: '任务时长',
								key: 'duration'
							},
							2: {
								title: '签到签退',
								key: 'sign'
							}
						};

						let arr = res.map((item, i) => {
							let list = [];
							item.data.map(e => {
								list.push({ name: e.name == '逾期' ? '超时' : e.name, value: e.value });
							});

							return {
								title: taskMap[i].title,
								key: taskMap[i].key,
								list,
							};
						});
						arr.splice(1, 0, {
							title: '逾期情况',
							key: 'overdue',
							list: [
								{
									name: '已逾期',
									value: '2'
								},
								{
									name: '未逾期',
									value: '1'
								}
							]
						});
						this.filterList = arr;
						if (this.typeForm != 2) {
							this.filterList.unshift({ key: 'planStatus', title: '工单状态', list: [{ value: 2, name: '进行中' }, { value: 3, name: '已提交' }, { value: 5, name: '维保签字' }, { value: 4, name: '签字完成' }] });
							console.log(this.filterList, 9999);
						}
						this.setKeyMap(this.filterList);
					}
				});
			} else if (index == 1) {
				let list = [{ title: '报障状态', key: 'elevatorStop', list: [{ name: '停梯', value: 2 }, { name: '正常', value: 1 }] }];
				problemItem({})
					.then(res => {
						// console.log(res,"故障现象");
						let arr = res.data.map(e => {
							return {
								name: e.dictValue,
								value: e.dictKey
							};
						});
						this.filterList = [...list, { title: '故障现象', key: 'problemItems', list: arr }, {
							title: '签到签退', key: 'sign',
							list: [{ name: '正常', value: 1 }, { name: '签到定位异常', value: 2 }, { name: '签退定位异常', value: 3 }, { name: '系统签退', value: 4 }]
						}];
						if (this.typeForm != 2) {
							this.filterList.unshift({ key: 'planStatus', title: '工单状态', list: [{ name: '进行中', value: 3 }, { name: '已完成', value: 4 }] });
						}
						this.setKeyMap(this.filterList);
					});
			} else {
				this.filterList = [{
					title: '签到签退', key: 'sign',
					list: [{ name: '正常', value: 1 }, { name: '签到定位异常', value: 2 }, { name: '签退定位异常', value: 3 }, { name: '系统签退', value: 4 }]
				}];
				if (this.typeForm != 2) {
					this.filterList.unshift({ key: 'planStatus', title: '工单状态', list: [{ name: '进行中', value: 6 }, { name: '已完成', value: 7 }] });
				}
				this.setKeyMap(this.filterList);
			}
			this.choosed = JSON.parse(JSON.stringify(this.csd));
			this.dateObj = JSON.parse(JSON.stringify(this.dateOpt));
			// console.log(this.dateObj,"model里面的值");

			if (Object.keys(this.choosed).length || this.dateObj.startTime) {
				this.activeTxt = true;
			} else {
				this.activeTxt = false;
			}
			// console.log();
		},
		// 关闭操作
		handleClose() {
			this.showFilter = false;
			// console.log(this.dateOpt,"handleClose看看时间");
			let obj = {};
			this.chooseArr.forEach(item => {
				if (obj[item.key]) {
					obj[item.key].push(item.value);
				} else {
					obj[item.key] = [];
					obj[item.key].push(item.value);
				}
			});
			this.choosed = obj;

			// console.log(this.choosed,"关闭选择")

			// 日期父组件接受日期默认值
			this.$nextTick(() => {
				this.$refs['filter-drawer'].initData(obj, this.dateObj);
			});
		},
		// 打开对话框
		showFuc() {
			if (this.disabled) {
				return;
			}
			setTimeout(() => {
				this.showFilter = true;
				// 初始化组组件
				console.log(this.dateObj, '打开获取日期');
				this.$refs['filter-drawer'].initData(this.choosed, this.dateOpt);

				let obj = { allChecked: this.allChecked, choosed: this.choosed, ...this.dateOpt };

				this.handleCount(obj);
			}, 500);
		},
		// 完成筛选
		filterd(res) {
			this.$emit('filterd', {
				choosed: this.choosed,
				allChecked: this.allChecked,
				dateObj: JSON.parse(JSON.stringify(res.dateObj))
			});
		},
		// 接受父组件保存按钮的操作
		submitFilter(res) {
			console.log(res, '确定');
			this.keyMap = res.keyMap;
			// console.log(this.keyMap, 222);
			this.allChecked = res.allChecked;
			this.choosed = JSON.parse(JSON.stringify(res.choosed));

			this.showFilter = false;
			if (res.dateObj) {
				this.dateObj = JSON.parse(JSON.stringify(res.dateObj));
			}

			if (Object.keys(this.choosed).length || this.dateObj.startTime) {
				this.activeTxt = true;
			} else {
				this.activeTxt = false;
			}
			this.setChooseArr();
			this.filterd(res);
		},

		// 删除筛选item
		removeItem(item, index) {
			// console.log(222);
			// this.showFilter=true
			this.showFuc();
			return;
		},

		// 渲染已选标签
		setChooseArr() {
			let filterList = this.filterList;
			if (this.allChecked) {
				this.chooseArr = [];
				return;
			}
			let arr = [];
			for (let key in this.choosed) {
				let obj = this.filterList.find((item, i) => {
					return item.key === key;
				});
				console.log(obj, 'obj的值set的值');
				if (obj) {
					obj.list.forEach(e => {
						if (this.choosed[key].indexOf(e.value) != -1) {
							arr.push({
								...e,
								key
							});
						}
					});
				}
			}

			this.chooseArr = arr;
			// console.log(this.chooseArr, 'this.chooseArr');
		},

		setKeyMap(list) {
			const map = new Map();
			list.forEach(item => {
				map.set(item.key, { flag: false });
			});
			const obj = [...map.entries()].reduce((obj, [key, value]) => ((obj[key] = value), obj), {});
			// console.log(obj, 'flagMap');
			this.keyMap = obj;
		},

		getListTotal(obj) {
			return new Promise((resolve, reject) => {
				let typeQueryArr = [orderReordByOld, orderReordWxOld, orderReordPjOld];
				typeQueryArr[this.orderType](obj)
					.then(res => {
						if (res) {
							resolve(res.data);
						}
					})
					.catch(() => {
						resolve({});
					});
			});
		},
		// 点击标签的时候
		getResultCount(res) {
			this.startTime = res.startTime;
			this.handleCount(res);
		},
		// 获取点击筛选条件后的数量总数
		async handleCount(res) {
			// console.log(res,'这里是计算');
			const { allChecked, choosed, startTime, endTime } = res;

			let params = {
				current: 1,
				size: 1,
				startTime: this.typeForm == 2 ? startTime : this.start,
				endTime: this.typeForm == 2 ? endTime : this.end,
				userIds: this.userIds,
				keyword: this.keyword,
				// planStatus:this.typeForm==2?[[4,4,7][this.orderType]]:''
			};
			let query = {};
			// if (Object.keys(choosed).length || allChecked||startTime!==null) {
			if (Object.keys(choosed).length) {
				const map = new Map();

				for (let key in choosed) {
					map.set(key, choosed[key]);
				}
				const obj = [...map.entries()].reduce((obj, [key, value]) => ((obj[key] = value.join(',')), obj), {});

				query = obj;
			}

			const tempList = ['startTime', 'endTime', 'current', 'size', 'keyword'];
			// if(this.typeForm!=2){
			// 	tempList.push('planStatus')
			// }
			// 如果有选择参数
			let tempParams = Object.keys(choosed).length ? { ...query, ...params } : params;
			for (let key in tempParams) {
				if (!tempList.includes(key)) {
					tempParams[key] = tempParams[key].split(',');
				}
			}
			// 如果是个人工单跳进来写死已完成的
			let planStatusParams = {};
			if (this.typeForm == 2 || choosed.planStatus && choosed.planStatus.length) {
				if (this.typeForm == 2) {
					planStatusParams.planStatus = [[4, 4, 7][this.orderType]];
				} else {
					planStatusParams.planStatus = choosed['planStatus'];
				}
			}
			// 获取请求的数据
			let count = await this.getListTotal(removeEmpty(Object.keys(planStatusParams).length ? { ...tempParams, ...planStatusParams } : tempParams));

			// console.log(count.total,"数值");
			if (count.total > 0) {
				this.comfireText = `查看${count.total}条数据`;
			} else {
				uni.showToast({
					icon: 'none',
					title: '筛选结果为空 请重新选择条件'
				});
				this.comfireText = '完成';
			}
			// }
		}
	}
};
</script>

<style lang="scss" scoped>
.filter-model {
	.imgBox {
		display: flex;

		image {
			width: 32rpx;
			height: 32rpx;
		}
	}

	width: 100%;

	.model-content {
		// width: calc(100% - 40rpx);
		// padding: 0 20rpx;
		display: flex;
		font-size: 26rpx;
		color: #333;
		// padding-bottom: 20rpx;
		align-items: center;
		justify-content: flex-end;

		&-title {
			// width: 80rpx;
			// margin-right: 20rpx;
			display: flex;
			// font-weight: bold;
			letter-spacing: 1rpx;
			align-items: center;

			image {
				width: 22rpx;
				height: 22rpx;
				transition: 0.3s all;
				margin: 4rpx 0rpx 0 7rpx;
			}

			.line {
				width: 2rpx;
				height: 30rpx;
				background-color: #ccc;
				margin-left: 12rpx;
			}
		}

		&-all {
			font-size: 24rpx;
			color: #999;
			margin-left: 12rpx;
		}

		&-tags {
			flex: 1;
			display: flex;
			flex-wrap: wrap;

			&-item {
				border: 2rpx solid #cccccc;
				padding: 0 4rpx 2rpx 8rpx;
				color: #666;
				border-radius: 4rpx;
				margin: 10rpx;
				font-size: 24rpx;

				image {
					width: 20rpx;
					height: 20rpx;
				}
			}
		}
	}
}
</style>
